import React, { useEffect, useState } from 'react';
import { LockOutlined, UserOutlined, CodeSandboxOutlined } from '@ant-design/icons';
import { message } from 'antd';
import { ProFormText, LoginForm } from '@ant-design/pro-form';
import { history, FormattedMessage, useModel } from 'umi';
import Footer from '@/components/Footer';
import { login, getCode } from '@/services/admin/common/api';
import { setLocalStorage } from '@/utils/LocalStorage';
import styles from './index.less';

const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s: any) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };

  const [configInfo, setConfigInfo] = useState<any>({});
  const [codeData, setCodeData] = useState<any>({});
  const setCode = async () => {
    const res = await getCode();
    if (res.status === 20000) {
      await setCodeData(res.data.codeData);
    }
  };
  const fetchApi = async () => {
    const config = await initialState?.fetchConfigInfo?.();
    if (config) {
      await setInitialState((s: any) => ({
        ...s,
        currentConfig: config,
      }));
    }
    await setConfigInfo(config);
    if (initialState?.currentUser?.username) {
      if (!history) return;
      const { query } = history.location;
      const { redirect } = query as { redirect: string };
      history.push(redirect || '/');
    }
    await setCode();
  };
  useEffect(() => {
    fetchApi();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const handleSubmit = async (values: any) => {
    values.key = codeData.key;
    try {
      // 登录
      const res = await login({ ...values });
      if (res.status === 20000) {
        message.success(res.message);
        await setLocalStorage('token', res.data.token);
        await setLocalStorage('expires_in', res.data.expires_in);
        await setLocalStorage('token_type', res.data.token_type);
        await fetchUserInfo();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        // const { query } = history.location;
        // const { redirect } = query as { redirect: string };
        history.push(res.data.admin_url);
        return;
      } else {
        setCode();
      }
    } catch (error) {
      message.error('登录失败，请重试');
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          logo={<img alt="logo" src={configInfo && configInfo.logo_image} />}
          title={configInfo && configInfo.name}
          subTitle={configInfo && configInfo.keywords}
          initialValues={{
            username: '',
            password: '',
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginType);
          }}
        >
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={styles.prefixIcon} />,
              }}
              placeholder={'请输入用户名!'}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.username.required"
                      defaultMessage="请输入用户名!"
                    />
                  ),
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon} />,
              }}
              placeholder={'请输入密码！'}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.password.required"
                      defaultMessage="请输入密码！"
                    />
                  ),
                },
              ]}
            />
            <div className={styles.codeBox}>
              <ProFormText
                name="captcha"
                fieldProps={{
                  size: 'large',
                  prefix: <CodeSandboxOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请输入验证码!'}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.captcha.required"
                        defaultMessage="请输入验证码!"
                      />
                    ),
                  },
                ]}
              />
              <div className={styles.imgBox}>
                <img
                  src={codeData.img}
                  alt="看不清，换一张"
                  onClick={() => {
                    setCode();
                  }}
                />
              </div>
            </div>
          </>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
